package com.dd.stack.redis.service.inner.impl;

import com.dd.stack.redis.config.redisConfig.RedisKeyFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/1/30 16:39
 * @Description RedisCounterService计数器实现
 */
@Service
public class RedisCounterServiceImpl {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 增加产品的访问计数
     * @param productId 产品ID
     */
    public void incrementProductCounter(Long productId) {
        String key = RedisKeyFactory.productCounterKey(productId);
        // 使用 INCR 命令增加计数
        redisTemplate.opsForValue().increment(key);
        // 设置过期时间，例如1天后过期
        redisTemplate.expire(key, 1, TimeUnit.DAYS);
    }

    /**
     * 获取产品的访问计数
     * @param productId 产品ID
     * @return 当前计数
     */
    public long getProductCounter(Long productId) {
        String key = RedisKeyFactory.productCounterKey(productId);
        Long count = (Long) redisTemplate.opsForValue().get(key);
        return count == null ? 0 : count;
    }
}